package com.wengzw.gateway.handler;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wengzw.commonutils.JwtUtils;
import com.wengzw.gateway.common.ResponseResult;
import com.wengzw.gateway.common.ResultCode;
import com.wengzw.gateway.config.JwtProperties;
import com.wengzw.gateway.config.TokenDao;
import com.wengzw.gateway.entity.AuthUserDetails;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.WebFilterChainServerAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;
import static com.wengzw.gateway.common.Constant.TOKEN_USER_INFO;


@Component
public class AuthenticationSuccessHandler extends WebFilterChainServerAuthenticationSuccessHandler {

    public final JwtProperties jwtProperties;
    private final TokenDao tokenDao;

    public AuthenticationSuccessHandler(JwtProperties jwtProperties,TokenDao tokenDao) {
        this.jwtProperties = jwtProperties;
        this.tokenDao = tokenDao;
    }

    @Override
    public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
        System.out.println("成功");
        ServerWebExchange exchange = webFilterExchange.getExchange();
        ServerHttpResponse response = exchange.getResponse();
        //设置headers
        HttpHeaders headers = response.getHeaders();
        headers.add("Content-Type", "application/json;charset=UTF-8");
        headers.add("Cache-Control", "no-store,no-cache,must-revalidate,max-age-8");
        headers.add("Access-Control-Allow-Origin","*");
        //设置body
        ResponseResult<AuthUserDetails> result = ResponseResult.success();
        byte[] dataBytes;
        ObjectMapper mapper = new ObjectMapper();
        try {
            User user = (User) authentication.getPrincipal();
            AuthUserDetails userDetails = buildUser(user);
            Map<String, Object> map = new HashMap<>(2);
            map.put(TOKEN_USER_INFO, userDetails);
            String jwtToken = JwtUtils.getJwtToken(user.getUsername(),null);
            //存到redis里
            System.out.println("用户名："+user.getUsername());
            tokenDao.setToken(user.getUsername(), jwtToken);
            userDetails.setToken(jwtToken);
            result.setData(userDetails);
            dataBytes = mapper.writeValueAsBytes(result);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            HashMap<String, Object> map = new HashMap<>(4);
            map.put("status", ResultCode.UNAUTHORIZED.getCode());
            map.put("msg", ResultCode.UNAUTHORIZED.getMsg());
            dataBytes = JSON.toJSONString(map).getBytes();
        }
        DataBuffer bodyDateBuffer = response.bufferFactory().wrap(dataBytes);
        return response.writeWith(Mono.just(bodyDateBuffer));
    }

    private AuthUserDetails buildUser(User user) {
        AuthUserDetails authUserDetails = new AuthUserDetails();
        // 获取数据库中的用户信息
        authUserDetails.setMobile(user.getUsername());
        authUserDetails.setPassword(user.getPassword());
        authUserDetails.setRole("admin");
        return authUserDetails;
    }
}
